var express = require('express')
var router = express.Router()
var bodyParser = require('body-parser')
var md5 = require('md5-node')

var DB = require('../../modules/db.js')

router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())

router.get('/', function(res, req) {
  res.render('login')
})
app.get('/login', function(req, res) {
  res.render('login')
})
router.post('/doLogin', function(req, res) {
  var username = req.body.username
  var password = md5(req.body.password)
  DB.find('user', { username, password }, function(err, data) {
    if (data.length > 0) {
      console.log('登录成功')
      req.ression.userinfo = data[0]
      res.redirect('/product') //登录成功后跳到product路由
    } else {
      res.send('<script>alert("登录失败"); location.href = "/login"</script>')
    }
  })
})
router.get('/loginOut', function(req, res) {
  req.session.destroy(function(err) {
    if (err) {
      console.error(err)
    } else {
      res.redirect('/login')
    }
  })
})

module.exports = router
